package com.to.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 *  druid 连接池工具类
 */
public class DruidUtils {

    /**
     * 创建连接池对象
     * @return druid 数据库连接池
     */
    public static DataSource getDataSource() {
        // 读取配置文件
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
        // 创建属性对象
        Properties p = new Properties();
        // 将读取配置存放到属性对象中
        DataSource dataSource = null;
        try {
            p.load(in);
            // 创建数据源(连接池对象)
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataSource;
    }

    /**
     * 创建数据库连接
     * @return 数据库连接
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }


}
